//
//  SLEditInfoViewController.m
//  SecondLoan
//
//  Created by 姚永波 on 2019/8/25.
//  Copyright © 2019 姚永波. All rights reserved.
//

#import "SLEditInfoViewController.h"
#import "SLAddressView.h"
#import "SLWorkView.h"
#import "SLBankEduView.h"
#import "SLBankFamilyView.h"
#import "BankInfoObject.h"
#import "SLSingleChoseView.h"
#import "SLEduView.h"
#import "MyMoneyRangeModel.h"
#import "SLVerifySubmitViewController.h"
#import "SLVerifyFailedViewController.h"
#import "CommonModelTypeDIc.h"
#import "NSString+Tools.h"
#import "PersonInfoObject.h"

const int row_edit = 5 + 7 + 4 + 6;
#define kVertiacalMarge 10

@interface SLEditInfoViewController ()<SLAddressViewDelegate,SLWorkViewDelegate,SLBankEduViewDelegate,SLBankFamilyViewDelegate>

@property (strong, nonatomic) UIScrollView *containScrollView;
@property (strong, nonatomic) SLAddressView *addressView;
@property (strong, nonatomic) SLWorkView *workView;
@property (strong, nonatomic) SLBankEduView *eduView;
@property (strong, nonatomic) SLBankFamilyView *familyView;
@property (strong, nonatomic) UIButton *btnSave;

@property (strong, nonatomic) BankInfoObject *personInfo;
@property (strong, nonatomic) MyMoneyRangeModel *myMoneyRange;
@property (strong, nonatomic) PersonInfoObject *proxyPersonInfo;

@end

@implementation SLEditInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"完善资料";
    self.view.backgroundColor = COLOR_White;
    [self.view addSubview:self.containScrollView];
    [self.containScrollView addSubview:self.addressView];
    [self.containScrollView addSubview:self.workView];
    [self.containScrollView addSubview:self.eduView];
    [self.containScrollView addSubview:self.familyView];
    [self.view addSubview:self.btnSave];
    [self loadData];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)loadData{
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObject:[UserLocal token] forKey:@"token"];
    [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_bank_info) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
        [self HUDdismiss];
        if (!error) {
            self.personInfo = [BankInfoObject mj_objectWithKeyValues:responseObject[@"data"][@"appBankInfo"]];
            if (self.personInfo == nil) {
                
                self.proxyPersonInfo = [PersonInfoObject mj_objectWithKeyValues:responseObject[@"data"]];

                BankInfoObject *infoObj = [BankInfoObject new];
                if (self.proxyPersonInfo.appEduInfoList != nil && [self.proxyPersonInfo.appEduInfoList count] > 0 ) {
                    EduInfoModel *eduM = self.proxyPersonInfo.appEduInfoList[0];
                    infoObj.highEdu = eduM.highEdu;
                    infoObj.schoolName = eduM.schoolName;
                    infoObj.graduationTime = eduM.graduationTime;
                }
                if (self.proxyPersonInfo.peronModel != nil ) {
                    infoObj.marStatus = self.proxyPersonInfo.peronModel.marStatus;
                }
                if (self.proxyPersonInfo.addressModel != nil) {
                    infoObj.address = self.proxyPersonInfo.addressModel.address;
                    infoObj.reside = self.proxyPersonInfo.addressModel.addressType;
                }
                if (self.proxyPersonInfo.workModel != nil) {
                    infoObj.industryType = self.proxyPersonInfo.workModel.industryType;
                    infoObj.companyName = self.proxyPersonInfo.workModel.companyName;
                    infoObj.workPost = self.proxyPersonInfo.workModel.workPost;
//                    infoObj.occupation = self.proxyPersonInfo.workModel.occupation;
                }
//                infoObj.yearSalary = nil;
//                infoObj.childNum = nil;
//                infoObj.personNum = nil;
                self.personInfo = infoObj;
            }
            self.eduView.model = self.personInfo;
            self.addressView.model = self.personInfo;
            self.workView.model= self.personInfo;
            self.familyView.model = self.personInfo;
        } else {
            [self HUDshowErrorWithStatus:error.localizedDescription];
        }
    }];
}

- (void)saveAction:(UIButton *)sender{
    if (isEmptyString(self.addressView.model.familyAddress) ) {
        [self HUDshowErrorWithStatus:@"请输入家庭详细地址"];
        return;
    }
    if (isEmptyString(self.addressView.model.address) ) {
        [self HUDshowErrorWithStatus:@"请输入居住详细地址"];
        return;
    }
    if (isEmptyString(self.addressView.addressHouseType.lblContent.text)) {
        [self HUDshowErrorWithStatus:@"请选择住房类型"];
        return;
    }
    if (isEmptyString(self.addressView.model.postCode) ) {
        [self HUDshowErrorWithStatus:@"请输入城市邮编"];
        return;
    }else if (![NSString validateZipCode:self.addressView.model.postCode]) {
        [self HUDshowErrorWithStatus:@"请输入正确城市邮编"];
        return;
    }
    if (isEmptyString(self.workView.industryView.lblContent.text)) {
        [self HUDshowErrorWithStatus:@"请选择所属行业"];
        return;
    }
    if (self.workView.model.occupation == 0 || isEmptyString(self.workView.jobViewView.lblContent.text)) {
        [self HUDshowErrorWithStatus:@"请选择职业"];
        return;
    }
    if (isEmptyString(self.workView.model.companyName)) {
        [self HUDshowErrorWithStatus:@"请输入公司名称"];
        return;
    }
    if (self.workView.model.workPost == 0 || isEmptyString(self.workView.jobViewView.lblContent.text)) {
        [self HUDshowErrorWithStatus:@"请选择职务"];
        return;
    }
    if (self.workView.model.yearSalary == 0) {
        [self HUDshowErrorWithStatus:@"请输入年收入"];
        return;
    }
    if(isEmptyString(self.workView.model.workTime)){
        [self HUDshowErrorWithStatus:@"请选择工作时间"];
        return;
    }
    if(self.eduView.model.highEdu == 0 || isEmptyString(self.eduView.highEduView.lblContent.text)){
        [self HUDshowErrorWithStatus:@"请选择最高学历"];
        return;
    }
    if (isEmptyString(self.eduView.model.schoolName)) {
        [self HUDshowErrorWithStatus:@"请输入学校名称"];
        return;
    }
    
    if (isEmptyString(self.eduView.model.graduationTime)) {
        [self HUDshowErrorWithStatus:@"请选择毕业时间"];
        return;
    }
    if (self.familyView.model.personNum == 0 || isEmptyString(self.familyView.personNumberView.lblContent.text)) {
        [self HUDshowErrorWithStatus:@"请选择家庭人数"];
        return;
    }
    if (isEmptyString(self.familyView.childHaveView.lblContent.text)) {
        [self HUDshowErrorWithStatus:@"请选择是否有子女"];
        return;
    }
    if ([self.familyView.model.haveChild isEqualToString:@"T"]) {
        if (self.familyView.model.childNum == 0 || isEmptyString(self.familyView.childNumberView.lblContent.text)) {
            [self HUDshowErrorWithStatus:@"请选择子女人数"];
            return;
        }
    }else{
        self.familyView.childNumberView.lblContent.text = @"0";
        self.familyView.model.childNum = 0;
    }
    if (self.familyView.model.marStatus == 0 || isEmptyString(self.familyView.marView.lblContent.text)) {
        [self HUDshowErrorWithStatus:@"请选择婚姻状况"];
        return;
    }
    if (isEmptyString(self.eduView.model.loanPurpose)) {
        [self HUDshowErrorWithStatus:@"请选择贷款用途"];
        return;
    }
    
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObject:[UserLocal token] forKey:@"token"];
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"id"] = self.personInfo.modelId > 0 ? @(self.personInfo.modelId):nil;
    dic[@"familyAddress"] = isEmptyString(self.addressView.model.familyAddress)?@"":self.addressView.model.familyAddress;
    dic[@"address"] = isEmptyString(self.addressView.model.address)?@"":self.addressView.model.address;
    dic[@"reside"] = @(self.addressView.model.reside);
    dic[@"postCode"] = self.addressView.model.postCode;
    dic[@"industryType"] = isEmptyString(self.workView.model.industryType)?@"":self.workView.model.industryType;
    dic[@"occupation"] = @(self.workView.model.occupation);
    dic[@"companyName"] = isEmptyString(self.workView.model.companyName)?@"":self.workView.model.companyName;
    dic[@"workPost"] = @(self.workView.model.workPost);
    dic[@"yearSalary"] = @(self.workView.model.yearSalary);
    dic[@"workTime"] = isEmptyString(self.workView.model.workTime)?@"":self.workView.model.workTime;
    dic[@"highEdu"] = @(self.eduView.model.highEdu);
    dic[@"schoolName"] = isEmptyString(self.eduView.model.schoolName)?@"":self.eduView.model.schoolName;
    dic[@"graduationTime"] = isEmptyString(self.eduView.model.graduationTime)?@"":self.eduView.model.graduationTime;
    dic[@"personNum"] = @(self.familyView.model.personNum);
    dic[@"childNum"] = @(self.familyView.model.childNum);
    dic[@"haveChild"] = self.familyView.model.haveChild;
    dic[@"marStatus"] = @(self.familyView.model.marStatus);
    dic[@"loanPurpose"] = self.familyView.model.loanPurpose;
    param[@"appBankInfo"] = dic;
    sender.enabled = NO;
    [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_user_bank_update) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
        sender.enabled = YES;
        [self HUDdismiss];
        if (!error) {
            // 获取额度接口 --- 跳转到审核状态界面
            NSMutableDictionary * param = [NSMutableDictionary dictionary];
            [param setObject:[UserLocal token] forKey:@"token"];
            [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_loan_apply_puhui) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
                NSInteger state = [responseObject[@"status"] integerValue];
                if(state == CodePuhuiLoanPassed){
                    SLVerifySubmitViewController *vc = [[SLVerifySubmitViewController alloc] initWithNibName:@"SLVerifySubmitViewController" bundle:nil];
                    vc.isPuhui = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }else if(state == 200){
                    SLVerifySubmitViewController *vc = [[SLVerifySubmitViewController alloc] initWithNibName:@"SLVerifySubmitViewController" bundle:nil];
                    vc.isPuhui = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    [self HUDshowErrorWithStatus:responseObject[@"msg"]];
                }
            }];
        } else {
            [self HUDshowErrorWithStatus:error.localizedDescription];
        }
    }];
}

#pragma mark ---- SLAddressViewDelegate ---
-(void)chooseAddresTypeView:(InfoChooseView *)chooseView
{
    SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc shareManager].arrayAddressType title:@"住房类型"] ;
    [view setEnterRowBlock:^(NSString * iterm, NSString * _Nonnull rowId) {
        self.addressView.addressHouseType.lblContent.text = iterm;
        self.addressView.model.reside = [rowId integerValue];
    }];
    [view popTo:nil];
}
#pragma mark ----- SLWorkViewDelegate --
- (void)chooseWorkView:(InfoChooseView *)view
{
    switch (view.tag) {
        case WorkIndustryTag:
           {
               SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc shareManager].arrayWorkType title:@"所在行业"] ;
               [view setEnterRowBlock:^(NSString * iterm, NSString * _Nonnull rowId) {
                   self.workView.industryView.lblContent.text = iterm;
                   self.workView.model.industryType = rowId;
               }];
               [view popTo:nil];
           }
            break;
        case WorkJobTag:
        {
            SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc shareManager].arrayWorkOccupation title:@"选择工作类型"] ;
            [view setEnterRowBlock:^(NSString * iterm, NSString * _Nonnull rowId)  {
                self.workView.jobViewView.lblContent.text = iterm;
                self.workView.model.occupation = [rowId integerValue];
            }];
            [view popTo:nil];
        }
            break;
        case WorkPositionTag:
        {
            SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc shareManager].arrayWorkPost title:@"选择职位"] ;
            [view setEnterRowBlock:^(NSString * iterm, NSString * _Nonnull rowId)  {
                self.workView.positionView.lblContent.text = iterm;
                self.workView.model.workPost = [rowId integerValue];
            }];
            [view popTo:nil];
        }
            break;
        case WorkHourTag:
        {
            SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc arrayYearList] title:@"工作时间"] ;
            [view setEnterBlock:^(NSString * iterm) {
                self.workView.workHourView.lblContent.text = iterm;
                self.workView.model.workTime = iterm;
            }];
            [view popTo:nil];
        }
        default:
            break;
    }
}

#pragma mark ====== SLBankEduViewDelegate ================
- (void)chooseBankEduView:(InfoChooseView *)view{
    switch (view.tag) {
        case BankEduViewHighTag:
        {
            SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc shareManager].arrayHighEduType  title:@"学历"] ;
            [view setEnterRowBlock:^(NSString * iterm, NSString * _Nonnull rowId) {
                self.eduView.highEduView.lblContent.text = iterm;
                self.eduView.model.highEdu = [rowId integerValue];
            }];
            [view popTo:nil];
        }
            break;
        case BankEduViewTimeTag:
        {
            SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc arrayYearList] title:@"毕业时间"] ;
            [view setEnterBlock:^(NSString * iterm) {
                self.eduView.graduateTimeView.lblContent.text = iterm;
                self.eduView.model.graduationTime = iterm;
            }];
            [view popTo:nil];
        }
            break;
        default:
            break;
    }
}

#pragma mark ====== SLBankFamilyViewDelegate ========
- (void)chooseBankFamilyView:(InfoChooseView *)view
{
    switch (view.tag) {
        case BankFamilyViewPersonNumberTag:
        {
            SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc arrayFamilyNumber] title:@"家庭人数"] ;
            [view setEnterRowBlock:^(NSString * _Nonnull iterm, NSString * _Nonnull rowId) {
                self.familyView.personNumberView.lblContent.text = iterm;
                self.familyView.model.personNum = [iterm integerValue];
            }];
            [view popTo:nil];
        }
            break;
        case BankFamilyViewMarTag:
        {
            SLSingleChoseView *chooseView = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc shareManager].arrayMarriageType title:@"婚姻状况"] ;
            [chooseView setEnterRowBlock:^(NSString * _Nonnull iterm, NSString * _Nonnull rowId) {
                self.familyView.marView.lblContent.text = iterm;
                self.familyView.model.marStatus = [rowId integerValue] ;
            }];
            [chooseView popTo:nil];
        }
            break;
        case BankFamilyHaveChildTag:
        {
            SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc shareManager].arrayHavaChild title:@"是否有子女"] ;
            [view setEnterRowBlock:^(NSString * _Nonnull iterm, NSString * _Nonnull rowId){
                self.familyView.childHaveView.lblContent.text = iterm;
                self.familyView.model.haveChild = rowId;
                if ([self.familyView.model.haveChild isEqualToString:@"F"]) {
                    self.familyView.childNumberView.userInteractionEnabled = NO;
                    self.familyView.childNumberView.lblContent.text = @"";
                    self.familyView.model.childNum = 0;
                }else{
                    self.familyView.childNumberView.userInteractionEnabled = YES;
                }
            }];
            [view popTo:nil];
        }
            break;
        case BankFamilyViewChildTag:
        {
            SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc arrayFamilyNumber] title:@"子女人数"] ;
            [view setEnterRowBlock:^(NSString * _Nonnull iterm, NSString * _Nonnull rowId){
                self.familyView.childNumberView.lblContent.text = iterm;
                self.familyView.model.childNum = [iterm integerValue];
            }];
            [view popTo:nil];
        }
            break;
        case BankLoanViewPurposeTag:
        {
            SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc shareManager].arrayLoanPurpos title:@"贷款用途"] ;
            [view setEnterRowBlock:^(NSString * _Nonnull iterm, NSString * _Nonnull rowId){
                self.familyView.loanPurposeView.lblContent.text = iterm;
                self.familyView.model.loanPurpose = rowId;
            }];
            [view popTo:nil];
        }
            break;
        default:
            break;
    }
}

#pragma mark ---
- (UIScrollView *)containScrollView
{
    if (!_containScrollView) {
        _containScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake (0, KStatusBarAndNavigationBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT - KStatusBarAndNavigationBarHeight - 60 - KMagrinBottom )];
        _containScrollView.backgroundColor = ColorFromHex(0xF3F3F3);
        _containScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, row_edit * kInfoEditHeiht + 3 * kVertiacalMarge);
    }
    return _containScrollView;
}
- (SLAddressView *)addressView
{
    if (!_addressView) {
        _addressView = [[SLAddressView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kInfoEditHeiht * 5)];
        _addressView.delegate = self;
    }
    return _addressView;
}
- (SLWorkView *)workView{
    if (!_workView) {
        _workView = [[SLWorkView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.addressView.frame) + kVertiacalMarge, SCREEN_WIDTH, kInfoEditHeiht * 7)];
        _workView.delegate = self;
    }
    return _workView;
}
- (SLBankEduView *)eduView{
    if (!_eduView) {
        _eduView = [[SLBankEduView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.workView.frame) + kVertiacalMarge, SCREEN_WIDTH, kInfoEditHeiht * 4)];
        _eduView.delegate = self;
    }
    return _eduView;
}
- (SLBankFamilyView *)familyView{
    if (!_familyView) {
        _familyView = [[SLBankFamilyView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.eduView.frame) + kVertiacalMarge, SCREEN_WIDTH, kInfoEditHeiht * 6)];
        _familyView.delegate = self;
    }
    return _familyView;
}
- (UIButton *)btnSave{
    if (!_btnSave) {
        _btnSave = [UIButton buttonWithType:UIButtonTypeCustom];
//        CGFloat yOrigin =  row_edit * kInfoEditHeiht;
        _btnSave.frame = CGRectMake(10, SCREEN_HEIGHT - 55 - KMagrinBottom , SCREEN_WIDTH - 20, 50);
        [_btnSave setBackgroundImage:[UIImage imageNamed:@"btn_bg"] forState:UIControlStateNormal];
        [_btnSave addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
        [_btnSave setTitle:@"保存" forState:UIControlStateNormal];
        [_btnSave setTitleColor:COLOR_White forState:UIControlStateNormal];
        _btnSave.titleLabel.font = Font18Bold;
        _btnSave.titleLabel.textColor = COLOR_White;
    }
    return _btnSave;
}

@end
